<template>
  <div class="article-edit-container">
    <div class="edit-header">
      <h2 class="edit-title" style="color: #3998a9;">{{ isEdit ? '编辑文章' : '添加文章' }}</h2>
      <div class="action-buttons">
        <el-button type="primary" @click="submitForm" :loading="submitting">
          <el-icon>
            <Check />
          </el-icon> 保存
        </el-button>
        <el-button @click="cancel">
          <el-icon>
            <Close />
          </el-icon> 取消
        </el-button>
      </div>
    </div>

    <div class="edit-content">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-card shadow="never" class="form-section">
          <div class="section-title">基本信息</div>
          <el-row :gutter="24">
            <el-col :span="16">
              <el-form-item label="文章标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入文章标题" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="文章分类" prop="categoryId">
                <el-popover placement="bottom-start" :width="300" trigger="click"
                  v-model:visible="categoryPopoverVisible">
                  <template #reference>
                    <el-input v-model="selectedCategoryName" placeholder="请选择分类" readonly
                      :class="{ 'is-error': categoryError }">
                      <template #suffix>
                        <el-icon>
                          <ArrowDown />
                        </el-icon>
                      </template>
                    </el-input>
                  </template>

                  <div class="category-tree-container">
                    <div class="tree-header">
                      <span>选择分类</span>
                      <el-button type="text" size="small" @click="clearCategorySelection">
                        清除选择
                      </el-button>
                    </div>
                    <el-tree ref="categoryTreeRef" :data="categoryTreeData" :props="treeProps" node-key="id"
                      :highlight-current="true" :expand-on-click-node="false" @node-click="handleCategorySelect"
                      class="category-tree">
                      <template #default="{ node, data }">
                        <span class="custom-tree-node">
                          <span :class="{ 'category-name': true, 'inactive': !data.isActive }">
                            {{ node.label }}
                          </span>
                          <span v-if="!data.isActive" class="inactive-badge">已禁用</span>
                        </span>
                      </template>
                    </el-tree>
                  </div>
                </el-popover>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="文章摘要" prop="summary">
                <el-input v-model="form.summary" type="textarea" :rows="3" placeholder="请输入文章摘要（可选）" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="文章标签" prop="tags">
                <el-input v-model="form.tags" placeholder="请输入标签，多个标签用逗号分隔" />
                <div class="tags-tip">
                  <el-text size="small" type="info">例如：技术,前端,Vue,JavaScript</el-text>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card shadow="never" class="form-section">
          <div class="section-title">内容编辑</div>
          <el-form-item prop="content">
            <el-input v-model="form.content" type="textarea" :rows="15" placeholder="请输入文章内容" resize="none" />
          </el-form-item>
        </el-card>

        <el-card shadow="never" class="form-section">
          <div class="section-title">发布设置</div>
          <el-form-item label="文章状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio-button :label="0">存为草稿</el-radio-button>
              <el-radio-button :label="1">立即发布</el-radio-button>
              <el-radio-button :label="2">已下线</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-card>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, Close, ArrowDown } from '@element-plus/icons-vue'
import { addArticle, updateArticle, getArticleDetail, getArticleCategoryTree } from '@/api/article'
import { useAuthStore } from '@/stores/authStore'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

/* 是否为编辑模式 */
const isEdit = computed(() => !!route.params.id)

/* 表单相关 */
const formRef = ref(null)
const submitting = ref(false)

/* 分类树相关 */
const categoryTreeRef = ref(null)
const categoryPopoverVisible = ref(false)
const categoryTreeData = ref([])
const selectedCategoryName = ref('')
const categoryError = ref(false)

/* 树形组件配置 */
const treeProps = {
  children: 'children',
  label: 'articleCategoryName'
}

/* 表单数据 */
const form = reactive({
  id: '',
  title: '',
  categoryId: '',
  content: '',
  summary: '',
  tags: '',
  status: 0,
  userId: authStore.user?.id || ''
})

/* 表单校验规则 */
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [{ required: true, message: '请选择文章分类', trigger: 'change' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
  summary: [
    { max: 500, message: '文章摘要长度不能超过500个字符', trigger: 'blur' }
  ],
  tags: [
    { max: 500, message: '标签长度不能超过500个字符', trigger: 'blur' }
  ]
}

/* 加载分类树 */
const loadCategories = async () => {
  try {
    // 修改：传递正确的参数名，获取所有分类（包括禁用的）用于显示完整树形结构
    const { code, data, message } = await getArticleCategoryTree(false) // 传递 false 表示获取所有分类
    if (code === 200) {
      categoryTreeData.value = data || []
    } else {
      ElMessage.error(message || '加载分类失败')
    }
  } catch (e) {
    ElMessage.error('加载分类失败: ' + (e.message || '未知错误'))
  }
}

/* 处理分类选择 */
const handleCategorySelect = (data) => {
  // 只允许选择启用的分类
  if (!data.isActive) {
    ElMessage.warning('该分类已禁用，无法选择')
    return
  }

  form.categoryId = data.id
  selectedCategoryName.value = data.articleCategoryName
  categoryError.value = false
  categoryPopoverVisible.value = false

  // 高亮选中的节点
  categoryTreeRef.value?.setCurrentKey(data.id)
}

/* 清除分类选择 */
const clearCategorySelection = () => {
  form.categoryId = ''
  selectedCategoryName.value = ''
  categoryError.value = false
  categoryTreeRef.value?.setCurrentKey(null)
}

/* 加载文章详情 */
const loadArticle = async (id) => {
  try {
    const { code, data, message } = await getArticleDetail(id)
    if (code === 200 && data) {
      Object.assign(form, {
        id: data.id,
        title: data.title,
        categoryId: data.categoryId,
        content: data.content,
        summary: data.summary || '',
        tags: data.tags || '',
        status: data.status,
        userId: data.userId || authStore.user?.id || ''
      })

      // 设置选中的分类名称
      if (data.categoryId) {
        const category = findCategoryById(categoryTreeData.value, data.categoryId)
        if (category) {
          selectedCategoryName.value = category.articleCategoryName
        }
      }
    } else {
      ElMessage.error(message || '加载文章失败')
    }
  } catch (e) {
    ElMessage.error('加载文章失败: ' + (e.message || '未知错误'))
  }
}

/* 根据ID查找分类 */
const findCategoryById = (categories, id) => {
  for (const category of categories) {
    if (category.id === id) {
      return category
    }
    if (category.children && category.children.length > 0) {
      const found = findCategoryById(category.children, id)
      if (found) return found
    }
  }
  return null
}

/* 提交：新增 / 编辑 */
const submitForm = async () => {
  try {
    // 触发表单校验
    await formRef.value.validate()
    submitting.value = true

    // 确保用户ID存在
    if (!authStore.user?.id) {
      throw new Error('用户信息不存在，请重新登录')
    }

    const payload = {
      title: form.title,
      categoryId: form.categoryId,
      content: form.content,
      summary: form.summary,
      tags: form.tags,
      status: form.status,
      userId: authStore.user.id
    }

    let resp
    if (isEdit.value) {
      payload.id = form.id
      resp = await updateArticle(payload)
    } else {
      resp = await addArticle(payload)
    }

    if (resp.code === 200) {
      ElMessage.success(isEdit.value ? '文章更新成功' : '文章添加成功')
      router.push({ name: 'ArticleList' })
    } else {
      ElMessage.error(resp.message || '操作失败')
    }
  } catch (err) {
    if (err === false) {
      ElMessage.warning('请正确填写表单')
    } else {
      console.error(err)
      ElMessage.error(err.message || '提交失败')
    }
  } finally {
    submitting.value = false
  }
}

/* 取消 */
const cancel = () => {
  ElMessageBox.confirm(
    '确定要取消编辑吗？未保存的内容将丢失',
    '提示',
    { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' }
  ).then(() => {
    router.push({ name: 'ArticleList' })
  })
}

/* 组件挂载 */
onMounted(async () => {
  await loadCategories()
  if (isEdit.value) {
    await loadArticle(route.params.id)
  }
})
</script>

<style scoped>
.article-edit-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.edit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.edit-title {
  font-size: 22px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.edit-content {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
}

.form-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

/* 分类树相关样式 */
.category-tree-container {
  max-height: 300px;
  overflow-y: auto;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 8px;
  font-weight: 500;
}

.category-tree {
  max-height: 250px;
  overflow-y: auto;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.category-name {
  flex: 1;
}

.category-name.inactive {
  color: #c0c4cc;
  cursor: not-allowed;
}

.inactive-badge {
  font-size: 12px;
  color: #f56c6c;
  background-color: #fef0f0;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 8px;
}

/* 标签相关样式 */
.tags-tip {
  margin-top: 8px;
  color: #909399;
}

/* 错误状态样式 */
.is-error {
  border-color: #f56c6c;
}

/* 禁用分类的树节点样式 */
.el-tree-node.is-disabled .el-tree-node__content {
  cursor: not-allowed;
  opacity: 0.6;
}

.el-tree-node.is-disabled .el-tree-node__content:hover {
  background-color: transparent;
}
</style>